package leetcode.ge100;

import leetcode.lt100.TreeNode;

import java.util.HashMap;

class Solution_106 {



    public static void main(String[] args) {
        int[] postorder = {2, 9, 15, 7, 20, 3};
        int[] inorder = {2, 9, 3, 15, 20, 7};
        new Solution_106().buildTree(inorder, postorder);
    }


    public TreeNode buildTree(int[] inorder, int[] postorder) {
        HashMap<Integer, Integer> idxMap = new HashMap<Integer, Integer>();
        int length = inorder.length;
        for (int i = 0; i < length; i++)
            idxMap.put(inorder[i], i);
        return buildTree(postorder, inorder, 0, length, 0, length, idxMap);
    }

    private TreeNode buildTree(int[] postorder, int[] inorder, int inStart, int inEnd, int postStart, int postEnd, HashMap<Integer, Integer> idxMap) {
        if (postStart >= postEnd) {
            return null;
        }
        int rootVal = postorder[postEnd - 1];
        TreeNode root = new TreeNode(rootVal);
        Integer inIndex = idxMap.get(rootVal);
        int leftNum = inIndex - inStart;
        root.left = buildTree(postorder, inorder, inStart, inIndex, postStart, postStart + leftNum, idxMap);
        root.right = buildTree(postorder, inorder, inIndex + 1, inEnd, postStart + leftNum, postEnd - 1, idxMap);
        return root;
    }

}